package com.zhc.dejingapi.service.upload.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhc.dejingapi.entity.QingAppfieldsEntity;
import com.zhc.dejingapi.entity.QingAppfieldtablevaluesEntity;
import com.zhc.dejingapi.entity.QingAppinfoEntity;
import com.zhc.dejingapi.mapper.QingAppfieldsMapper;
import com.zhc.dejingapi.mapper.QingAppfieldtablevaluesMapper;
import com.zhc.dejingapi.mapper.QingAppinfoMapper;
import com.zhc.dejingapi.pojo.qingflow.QingflowApiInfo;
import com.zhc.dejingapi.pojo.qingflow.appfield.QingFieldItemBase;
import com.zhc.dejingapi.pojo.qingflow.appfield.QingFieldItemTableRowValueBase;
import com.zhc.dejingapi.pojo.qingflow.appfield.QingFieldResultMainBase;
import com.zhc.dejingapi.pojo.qingflow.appfield.QingFieldRowDataBase;
import com.zhc.dejingapi.service.upload.IQingAppFieldService;
import com.zhc.dejingapi.utils.qing.QingFieldValueUtils;
import com.zhc.dejingapi.utils.qing.QingflowAPIUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class QingAppFieldServiceImpl implements IQingAppFieldService {

    @Autowired
    private QingAppinfoMapper qingAppinfoMapper;

    @Autowired
    private QingAppfieldsMapper qingAppfieldsMapper;

    @Autowired
    private QingAppfieldtablevaluesMapper qingAppfieldtablevaluesMapper;

    @Autowired
    QingflowApiInfo qqingflowApiInfo;
    @Qualifier("mySqlJdbcTemplate")
    @Autowired
    private JdbcTemplate mySqlJdbcTemplate;
    //private final JdbcTemplate mysqlJdbcTemplate;

    private final RedisTemplate<String,Object> redisTemplate;

    public QingAppFieldServiceImpl(@Qualifier("redisTemplateWin")RedisTemplate<String, Object> redisTemplate1) {
        this.redisTemplate = redisTemplate1;
    }


    @Override
    public boolean SynAppField() {
        try {
            //String strQingAccessToken= accessTokenUtils.getAccessToken(qqingflowApiInfo);

            //第一步，获取需要同步的appKey
            QueryWrapper<QingAppinfoEntity> queryappInfo = new QueryWrapper<>();
            queryappInfo.eq("is_needSyn", 1)
                    .eq("is_Delete", 0);
                    //.eq("appType", 0);
            List<QingAppinfoEntity> appInfoList = qingAppinfoMapper.selectList(queryappInfo);

            if (appInfoList == null || appInfoList.isEmpty() || appInfoList.size() == 0) {
                log.info("错误：列表为空！");
            } else {
                for (int i = 0; i < appInfoList.size(); i++) {



                    QingAppinfoEntity qingAppinfoEntityQuery = appInfoList.get(i);
                    log.info("开始同步appKey:" + qingAppinfoEntityQuery.getAppKey()+" appName:"+qingAppinfoEntityQuery.getAppName());
                    String strBody = "";
                    strBody += "{\n";//
                    strBody += "\"pageSize\": 1,\n";
                    strBody += "\"pageNum\": 1,\n";
                    strBody += "\"type\": 8,\n";
                    strBody += "\"sorts\": [],\n";
                    strBody += "\"queriesRel\": \"\",\n";
                    strBody += "\"queryKey\": \"\",\n";
                    strBody += "\"applyIds\": []\n";
                    strBody += "}";
                    QingFieldResultMainBase fieldResultMainBase = QingflowAPIUtils.GetAppFieldInfo(qqingflowApiInfo, qingAppinfoEntityQuery.getAppKey(), strBody);

                    if (fieldResultMainBase == null
                            || fieldResultMainBase.getResult() == null
                            || fieldResultMainBase.getResult().getResult() == null) {

                    } else {
                        if (fieldResultMainBase.getErrCode() == 0) {

                            if (fieldResultMainBase.getResult().getResult().isEmpty()) {

                            } else {

                                QingFieldRowDataBase rowDataBase = fieldResultMainBase.getResult().getResult().get(0);
                                if (rowDataBase == null || rowDataBase.getAnswers() == null || rowDataBase.getAnswers().isEmpty()) {

                                } else {
                                    System.out.println("rowDataBase.getAnswers().size():" + rowDataBase.getAnswers().size());

                                    for (int k = 0; k < rowDataBase.getAnswers().size(); k++) {

                                        QingFieldItemBase itemBase = rowDataBase.getAnswers().get(k);
                                        QueryWrapper<QingAppfieldsEntity> queryappField = new QueryWrapper<>();

                                        queryappField.eq("appMain_Id", qingAppinfoEntityQuery.getMainId())
                                                .eq("queId", itemBase.getQueId());

                                        if(itemBase.getValues()==null||itemBase.getValues().isEmpty()){
                                            //region 没有明细字段
                                            Long iCountField = qingAppfieldsMapper.selectCount(queryappField);
                                            long filedId =0;
                                            if (iCountField > 0) {
                                                //赋值
                                                QingAppfieldsEntity appfieldModify = qingAppfieldsMapper.selectOne(queryappField);
                                                appfieldModify = QingFieldValueUtils.CopyQingAppfieldsFromQingFieldItemBase(appfieldModify, itemBase);
                                                try{
                                                    qingAppfieldsMapper.update(appfieldModify, queryappField);
                                                }
                                                catch (Exception e){
                                                    e.printStackTrace();
                                                    throw  e;
                                                }
                                                //qingAppfieldsMapper.update(appfieldModify, queryappField);
                                                filedId = appfieldModify.getFieldId();

                                            } else {
                                                //赋值
                                                QingAppfieldsEntity appfieldAdd = new QingAppfieldsEntity();

                                                appfieldAdd = QingFieldValueUtils.CopyQingAppfieldsFromQingFieldItemBase(appfieldAdd, itemBase);
                                                appfieldAdd.setAppKey(qingAppinfoEntityQuery.getAppKey());
                                                appfieldAdd.setAppmainId(qingAppinfoEntityQuery.getMainId());

                                                //qingAppfieldsMapper.insert(appfieldAdd);
                                                try{
                                                    qingAppfieldsMapper.insert(appfieldAdd);
                                                }
                                                catch (Exception e){
                                                    e.printStackTrace();
                                                    throw  e;
                                                }
                                                filedId = appfieldAdd.getFieldId();
                                            }

                                            String strSql="delete from qing_appfieldtablevalues where field_Id=?";
                                            mySqlJdbcTemplate.update(strSql,filedId);

                                            List<QingFieldItemTableRowValueBase> listTableValues = itemBase.getTableValues()[0];


                                            for (int j = 0; j < listTableValues.size(); j++) {

                                                QingFieldItemTableRowValueBase itemTableValueBase = listTableValues.get(j);

                                                QingAppfieldtablevaluesEntity qingAppfieldTableValuesEntity = new QingAppfieldtablevaluesEntity();
                                                qingAppfieldTableValuesEntity=QingFieldValueUtils.CopyQingAppTableValueFieldsFromQingFieldItemBase(qingAppfieldTableValuesEntity,itemTableValueBase);
                                                qingAppfieldTableValuesEntity.setFieldId(filedId);

                                                //qingAppfieldtablevaluesMapper.insert(qingAppfieldTableValuesEntity);
                                                try{
                                                    qingAppfieldtablevaluesMapper.insert(qingAppfieldTableValuesEntity);
                                                }
                                                catch (Exception e){
                                                    e.printStackTrace();
                                                    throw  e;
                                                }
                                            }
                                            //endregion
                                        }
                                        else{


                                            //region 没有明细字段
                                            Long iCountField = qingAppfieldsMapper.selectCount(queryappField);
                                            if (iCountField > 0) {
                                                //赋值
                                                QingAppfieldsEntity appfieldModify = qingAppfieldsMapper.selectOne(queryappField);
                                                appfieldModify = QingFieldValueUtils.CopyQingAppfieldsFromQingFieldItemBase(appfieldModify, itemBase);
                                                try{
                                                    qingAppfieldsMapper.update(appfieldModify, queryappField);
                                                }
                                                catch (Exception e){
                                                    e.printStackTrace();
                                                    throw  e;
                                                }




                                            } else {
                                                //赋值
                                                QingAppfieldsEntity appfieldAdd = new QingAppfieldsEntity();

                                                appfieldAdd = QingFieldValueUtils.CopyQingAppfieldsFromQingFieldItemBase(appfieldAdd, itemBase);
                                                appfieldAdd.setAppKey(qingAppinfoEntityQuery.getAppKey());
                                                appfieldAdd.setAppmainId(qingAppinfoEntityQuery.getMainId());
                                                //qingAppfieldsMapper.insert(appfieldAdd);
                                                try{
                                                    qingAppfieldsMapper.insert(appfieldAdd);
                                                }
                                                catch (Exception e){
                                                    e.printStackTrace();
                                                    throw  e;
                                                }
                                                long filedId = appfieldAdd.getFieldId();


                                            }
                                            //endregion
                                        }


                                    }


                                }
                            }
                        } else {
                            log.error(fieldResultMainBase.getErrCode() + "\n" + fieldResultMainBase.getErrMsg());
                        }
                    }

                }
            }

        } catch (Exception e) {
            log.info(e.getMessage() + "\n" + e.getStackTrace());
            e.printStackTrace();
        }
        return false;
    }
}
